package com.hunktimes.wholesale.ui.pages

import android.Manifest
import android.app.Activity
import android.content.ContentResolver
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.database.Cursor
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.view.View
import androidx.activity.result.contract.ActivityResultContract
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.FileProvider
import com.hunktimes.wholesale.R
import com.hunktimes.wholesale.base.BasePageFragment
import com.hunktimes.wholesale.databinding.FragmentMemberInfoBinding
import com.hunktimes.wholesale.util.L
import com.hunktimes.wholesale.widget.PermissionDialog
import com.jianrui.msgvision.view.widget.BotOptionsDialog
import com.permissionx.guolindev.PermissionX
import java.io.File

/**
 * Author: Delete
 * Date: 2020/7/28 19:26
 * Description:
 *
 */

class MemberInfoFragment : BasePageFragment(R.layout.fragment_member_info) {
    override val titleRes: Int
        get() = R.string.title_member_info
    lateinit var viewBinding: FragmentMemberInfoBinding

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        viewBinding = FragmentMemberInfoBinding.bind(view)
    }

    override fun onStart() {
        super.onStart()
        viewBinding.changePwdBtn.setOnClickListener {
            rootNavController.navigate(R.id.action_navigation_member_info_to_navigation_change_pwd)
        }

        viewBinding.avatarIv.setOnClickListener {
            changeAvatar()
        }

    }

    fun changeAvatar() {
        BotOptionsDialog.Builder(requireContext()).apply {
            op1Text = "相机"
            op2Text = "从相册"
            op1Listener = object : DialogInterface.OnClickListener {
                override fun onClick(dialog: DialogInterface?, which: Int) {
                    dialog?.dismiss()
                    avatarFromCamera()
                }
            }
            op2Listener = object : DialogInterface.OnClickListener {
                override fun onClick(dialog: DialogInterface?, which: Int) {
                    dialog?.dismiss()
                    avatarFromGallery()
                }
            }
            op3Listener = object : DialogInterface.OnClickListener {
                override fun onClick(dialog: DialogInterface?, which: Int) {
                    dialog?.dismiss()
                }
            }
        }.build().show()
    }

    private val picturePreviewAction =
        registerForActivityResult(ActivityResultContracts.TakePicturePreview()) {
            it?.let {
                viewBinding.avatarIv.setImageBitmap(it)
            }
        }

    fun avatarFromCameraPreview() {
        permissionEnsure(Manifest.permission.CAMERA, onAllGranted = {
            L.d("avatarFromwCameraPreview onAllGranted")
            picturePreviewAction.launch(null)
        })
    }

    private val pictureAction =
        registerForActivityResult(ActivityResultContracts.TakePicture()) {
            L.d("avatarFromwCamera result -> $it")
            if (it) {
                val avatar = BitmapFactory.decodeStream(
                    requireContext().contentResolver.openInputStream(avatarCameraUri)
                )
                viewBinding.avatarIv.setImageBitmap(avatar)
            }
        }
    lateinit var avatarCameraUri: Uri
    fun avatarFromCamera() {
        val avatarFile = File(requireContext().externalCacheDir, "avatar")
        if (avatarFile.exists()) {
            avatarFile.delete()
        }
        avatarFile.createNewFile()
        avatarCameraUri =
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//sdk>24
                FileProvider.getUriForFile(
                    requireContext(),
                    "${requireContext().packageName}.fileProvider",
                    avatarFile
                )
            } else {
                Uri.fromFile(avatarFile)
            }
        pictureAction.launch(avatarCameraUri)
    }

    private val galleryAction by lazy {
        registerForActivityResult(GalleryPick(requireContext().contentResolver)) {
            viewBinding.avatarIv.setImageBitmap(it)
        }
    }

    fun avatarFromGallery() {
        permissionEnsure(
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            onAllGranted = {
                L.d("avatarFromGallery onAllGranted")
                galleryAction.launch(null)
            })
    }

    fun permissionEnsure(
        vararg permissions: String,
        onAllGranted: () -> Unit = {},
        onNotAllGranted: () -> Unit = {}
    ) {
        PermissionX.init(this)
            //.permissions(permissions.asList())
            .permissions(*permissions)
            .onExplainRequestReason { scope, deniedList, beforeRequest ->
                val message = "WholeSale需要您同意以下權限才能正常使用:"
                val dialog = PermissionDialog(requireContext(), message, deniedList)
                scope.showRequestReasonDialog(dialog)
            }.onForwardToSettings { scope, deniedList ->
                val message = "您需要去設置中手動開啟以下權限"
                val dialog = PermissionDialog(requireContext(), message, deniedList)
                scope.showForwardToSettingsDialog(dialog)
            }
            .request { allGranted, grantedList, deniedList ->
                if (allGranted) {
                    onAllGranted.invoke()
                } else {
                    onNotAllGranted.invoke()
                }
            }

    }
}

class GalleryPick(val contentResolver: ContentResolver) : ActivityResultContract<String, Bitmap>() {
    override fun createIntent(context: Context, input: String?): Intent {
        //Intent goAlbum = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        return Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    }

    override fun parseResult(resultCode: Int, intent: Intent?): Bitmap? {

        if (null == intent || resultCode != Activity.RESULT_OK) {
            return null
        } else {
            val uri = intent.data
            L.d("GalleryPick parseResult uri -> $uri")
            uri?.let {
                val filtPathCol = arrayOf(MediaStore.Images.Media.DATA)
                val cursor: Cursor? = contentResolver.query(
                    uri,
                    filtPathCol, null, null, null
                )
                cursor?.let {
                    cursor.moveToFirst()
                    val columnIndx = cursor.getColumnIndex(filtPathCol[0])
                    val filePath = cursor.getString(columnIndx)
                    L.d("GalleryPick parseResult filePath -> $filePath")
                    val bitmap: Bitmap = BitmapFactory.decodeFile(filePath)
                    L.d("GalleryPick parseResult bitmpap -> $bitmap")
                    cursor.close();
                    return bitmap
                }
            }
            return null
        }

    }

}